package com.majie.utils.utils.spring;

import org.springframework.context.annotation.Bean;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.mvc.method.RequestMappingInfo;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;

import javax.annotation.PostConstruct;
import java.util.Map;
import java.util.Set;

/**
 * 直接将内中代码放到Main类下
 */
public class ScanUrl {

    /**
     * 扫描URL,主要用于权限的时候
     */
    @PostConstruct  //这个注解很重要，可以在每次启动的时候检查是否有URL更新，RequestMappingHandlerMapping只能在controller层用。这里我们放在主类中
    public void detectHandlerMethods( ) {
        final RequestMappingHandlerMapping requestMappingHandlerMapping = requestMappingHandlerMapping();
        Map<RequestMappingInfo, HandlerMethod> map = requestMappingHandlerMapping.getHandlerMethods();
        Set<RequestMappingInfo> mappings = map.keySet();
        for (RequestMappingInfo info : mappings) {
            Set<RequestMethod> methods = info.getMethodsCondition().getMethods();
            if (methods.isEmpty()) {
                continue;
            }
            for (RequestMethod requestMethod : methods) {
                String name = requestMethod.name();
                System.out.println(name);
            }
            HandlerMethod method = map.get(info);
            String methodstr = method.toString();
            methodstr = methodstr.split("\\(")[0];
            methodstr = methodstr.split(" ")[2];
            int i = methodstr.lastIndexOf(".");
            methodstr = methodstr.substring(0, i);   // 方法名
            String urlparm = info.getPatternsCondition().toString();
            String url = urlparm.substring(1, urlparm.length() - 1);
            System.out.println(url);
        }
    }

    @Bean
    public RequestMappingHandlerMapping requestMappingHandlerMapping( ) {
        return new RequestMappingHandlerMapping();
    }
}
